<script setup lang="ts">
  import { addPatientApi, patientDetailApi, updatePatientApi } from '@/apis/patient'
  import type { PatientParams } from '@/types/patient'
  import { onLoad } from '@dcloudio/uni-app'
  import type { InputOnBlurEvent } from '@uni-helper/uni-app-types/index'
  import { ref } from 'vue'

  // 1. 表单数据
  const formData = ref<PatientParams>({
    name: '',
    idCard: '',
    gender: 1,
    defaultFlag: 1,
  })
  const nameRef = ref()
  const idCardRef = ref()
  const genderRef = ref()
  const form = ref()
  // 2. 表单验证规则
  const formRules = {
    name: {
      rules: [
        { required: true, errorMessage: '请填写患者姓名' },
        {
          pattern: /^[\u4e00-\u9fa5]{2,5}$/,
          errorMessage: '患者姓名为2-5位中文',
        },
      ],
    },
    idCard: {
      rules: [
        { required: true, errorMessage: '请输入身份证号' },
        {
          pattern:
            /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,
          errorMessage: '身份证号格式不正确',
        },
      ],
    },
    gender: {
      rules: [
        {
          required: true,
          errorMessage: '请选择性别',
        },
        {
          validateFunction: function (rule, value, data, callback) {
            // 定下规则 只能男生1 不能是女生
            if (parseInt(formData.value.idCard.at(-2)!) % 2 === 1 && formData.value.gender !== 1) {
              callback('只能男生 不能是女生')
            } else if (
              parseInt(formData.value.idCard.at(-2)!) % 2 === 0 &&
              formData.value.gender !== 0
            ) {
              callback('只能女生 不能是男生')
            }
            return true
          },
        },
      ],
    },
  }
  const onChange = (e) => {
    console.log(e.detail.value)
    formData.value.gender = e.detail.value
    genderRef.value.onFieldChange(formData.value.gender)
  }
  const onSubmit = async () => {
    try {
      await form.value?.validate?.()
      if (props.id) {
        const { name, idCard, defaultFlag, gender } = formData.value
        const params = { name, idCard, defaultFlag, gender, id: props.id }
        await updatePatientApi(params)
      } else {
        await addPatientApi(formData.value)
      }
      uni.showToast({
        title: props.id ? '编辑成功' : '添加成功',
        icon: 'none',
      })
      // 跳转到患者列表页面
      uni.navigateBack()
      console.log('通过')
    } catch (error) {
      console.log('不通过')
    }
  }
  // 切换默认就诊人
  const onDefaultChange = () => {
    if (formData.value.defaultFlag === 1) {
      formData.value.defaultFlag = 0
    } else {
      formData.value.defaultFlag = 1
    }
  }
  // 使用 defineProps 接收地址参数
  const props = defineProps<{
    id: string
  }>()
  //点击进入编辑
  // 生命周期（页面加载完成）
  onLoad(async () => {
    if (!props.id) {
      return
    }
    uni.setNavigationBarTitle({ title: '编辑患者' })
    const data = await patientDetailApi(props.id)
    formData.value = data
  })
</script>

<template>
  <scroll-page>
    <view class="archive-page">
      <uni-forms border label-width="220rpx" ref="form" :model="formData" :rules="formRules">
        <uni-forms-item label="患者姓名" name="name" ref="nameRef">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            v-model="formData.name"
            placeholder="请填写真实姓名"
            @blur="(e:InputOnBlurEvent) => nameRef.onFieldChange(e.detail.value)"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard" ref="idCardRef">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            v-model="formData.idCard"
            placeholder="请填写身份证号"
            @blur="(e:InputOnBlurEvent) => idCardRef.onFieldChange(e.detail.value)"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender" ref="genderRef">
          <uni-data-checkbox
            :value="formData.gender"
            @change="onChange"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="name">
          <view class="uni-switch">
            <switch
              color="#20c6b2"
              :checked="formData.defaultFlag === 1"
              @change="onDefaultChange"
              style="transform: scale(0.7)"
            />
          </view>
        </uni-forms-item>
        <button class="uni-button" @click="onSubmit">保存</button>
      </uni-forms>
    </view>
  </scroll-page>
</template>

<style lang="scss">
  @import './index.scss';
</style>
